package cn.zjxiliu.lib_core.utils;

import java.security.MessageDigest;

/**
 * Created by jessie on 2018/10/25.
 */

public class MD5Utils {
    private static final String TAG = "MD5Utils";
    // 用来将字节转换成 16 进制表示的字符
    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    private static ThreadLocal<MessageDigest> messageDigestHolder = new ThreadLocal<MessageDigest>();

    private MD5Utils() {

    }

    /***
     *
     * @Title: getMD5Format
     * @Description: 计算MD5并转换为32字节明文显示串
     * @author wujl
     * @param data
     * @return String 返回类型
     */
    public static String getMD5Format(String data) {
        try {
            MessageDigest message = messageDigestHolder.get();
            if (message == null) {
                message = java.security.MessageDigest.getInstance("MD5");
                messageDigestHolder.set(message);
            }
            message.update(data.getBytes("UTF-8"));
            byte[] b = message.digest();

            String digestHexStr = "";
            for (int i = 0; i < 16; i++) {
                digestHexStr += byteHEX(b[i]);
            }

            return digestHexStr;
        } catch (Exception e) {
            return null;
        }
    }

    /***
     *
     * @Title: byteHEX
     * @Description:
     * @author wujl
     * @param ib
     * @return String 返回类型
     */
    private static String byteHEX(byte ib) {
        char[] ob = new char[2];
        ob[0] = hexDigits[(ib >>> 4) & 0X0F];
        ob[1] = hexDigits[ib & 0X0F];
        return new String(ob);
    }

    public static void main(String[] args){
        String result = getMD5Format("13606606487");
        System.out.println("======result======");
        System.out.println(result);

    }

}
